package servlet.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import service.ConvertBooksType;
import service.SearchIndexpagere;
import service.ShoppingService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/shopping")
public class ShoppingSelect extends HttpServlet {
    private ConvertBooksType convertBooksType = new ConvertBooksType();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应对象类型
        resp.setContentType("application/json;charset=utf-8");
        // 从请求中获取参数
        String username = req.getParameter("username");
        //当前页数
        String currentPage = req.getParameter("currentPage");
        //每页展示的数据
        String pageSize = req.getParameter("pageSize");
        // 转换currentPage和pageSize为整数
        int page = Integer.parseInt(currentPage);
        int size = Integer.parseInt(pageSize);

        SearchIndexpagere searchIndexpagere = new SearchIndexpagere();
        ShoppingService shoppingService = new ShoppingService();
        List<pojo.Shopping> shoppings = shoppingService.selectShopping(username);
        // 计算起始索引和结束索引
        int startIndex = (page - 1) * size;
        int endIndex = Math.min(startIndex + size, shoppings.size());
        // 截取当前页的书籍数据
        List<pojo.Shopping> currentPageBooks = shoppings.subList(startIndex, endIndex);
//        String jsonString = JSON.toJSONString(books);
        JSONObject jsonResponse = new JSONObject();
        jsonResponse.put("shoping", currentPageBooks); // 添加books列表
        jsonResponse.put("size", shoppings.size()); // 添加books大小信息
        String jsonString = jsonResponse.toJSONString();
        PrintWriter writer = resp.getWriter();
        writer.write(jsonString);
    }
}
